/*
 * 广告活动管理
 * 新增活动
 * @date 2016/6/21
 */

// 城市选择
$(document).delegate(".cities-part", "click", function () {
    $(this).siblings('.cities-model').removeClass('display-none');
    $("#citiesAll").attr("checked", false);
    $("#citiesPart").attr("checked", true);
});

$(document).delegate(".cities-all", "click", function () {
    $(this).siblings('.cities-model').addClass('display-none');
    $("#citiesAll").attr("checked", true);
    $("#citiesPart").attr("checked", false);
});

//生成活动编号
$(document).delegate("#createActNO", "click", function () {
    var params = JSON.stringify({'type': Number($('#type option:selected').val())});
    $.ajax({
        type: "POST",
        url: "/admanager/createactno",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                $('#act_no').val(data.act_no);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
});

//活动类型改变清空活动编号
$(document).delegate("#type", "change", function () {
    delAppPicture();
    delWechatPicture();
    $('#act_no').val('');
});

//上传app端图片
$(document).delegate("#appUpload", "click", function () {
    if (!$('#act_no').val()) {
        bbx_alert_error("请先生成活动编号!");
        return;
    }
    var params = {'bucket': 'app', 'act_no': $('#act_no').val()};
    $.ajaxFileUpload({
        type: "POST",
        url: '/uploader/uploadTencentCloud',
        secureuri: false,
        fileElementId: 'appImg',
        dataType: 'json',
        contentType: "application/json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                for (var i = 0; i < data.info.length; i++) {
                    layer.msg('图片上传成功！', {icon: 1, time: 1000}, function () {
                        layer.closeAll();
                    });
                    $('#appImgName').text('');
                    $('#poster').attr('src', data.info[i].data.source_url + '?' + Math.random());
                    break;
                }
            } else {
                bbx_alert_error(data.message);
            }
        }
    });
});

//删除app端图片
$(document).delegate("#appDelete", "click", function () {
    delAppPicture();
});

function delAppPicture() {
    $('#appImgName').text('');
    $('#appImgMark').show();
    $('#appImg').after($('#appImg').clone().val(""));
    $('#appImg').remove();

    if (!$('#poster').attr('src') || !$('#act_no').val()) {
        return;
    }
    var params = JSON.stringify({'bucket': 'app', 'path': $('#poster').attr('src'), 'act_no': $('#act_no').val()});
    $.ajax({
        type: "POST",
        url: "/uploader/deleteTencentCloud",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                layer.msg('图片删除成功！', {icon: 1, time: 1000}, function () {
                    layer.closeAll();
                });
                $('#poster').attr('src', '');
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

//上传微信端图片
$(document).delegate("#wechatUpload", "click", function () {
    if (!$('#act_no').val()) {
        bbx_alert_error("请先生成活动编号!");
        return;
    }
    var params = {'bucket': 'wechat', 'act_no': $('#act_no').val()};
    $.ajaxFileUpload({
        type: "POST",
        url: '/uploader/uploadTencentCloud',
        secureuri: false,
        fileElementId: 'wechatImg',
        dataType: 'json',
        contentType: "application/json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                for (var i = 0; i < data.info.length; i++) {
                    layer.msg('图片上传成功！', {icon: 1, time: 1000}, function () {
                        layer.closeAll();
                    });
                    $('#wechatImgName').text('');
                    $('#wechat_poster').attr('src', data.info[i].data.source_url + '?' + Math.random());
                    break;
                }
            } else {
                bbx_alert_error(data.message);
            }
        }
    });
});

//删除微信端图片
$(document).delegate("#wechatDelete", "click", function () {
    delWechatPicture();
});

function delWechatPicture() {
    $('#wechatImgName').text('');
    $('#wechatImgMark').show();
    $('#wechatImg').after($('#wechatImg').clone().val(""));
    $('#wechatImg').remove();

    if (!$('#wechat_poster').attr('src') || !$('#act_no').val()) {
        return;
    }
    var params = JSON.stringify({'bucket': 'wechat', 'path': $('#wechat_poster').attr('src'), 'act_no': $('#act_no').val()});
    $.ajax({
        type: "POST",
        url: "/uploader/deleteTencentCloud",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                layer.msg('图片删除成功！', {icon: 1, time: 1000}, function () {
                    layer.closeAll();
                });
                $('#wechat_poster').attr('src', '');
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

// 页面初始化
$(function () {
    getProvice();
});

//获取省份城市
function getProvice() {
    $.ajax({
        type: "POST",
        url: "/common/getprovice",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"": ""}),
        success: function (data) {
            if (data.status == 0) {
                for (var i = 0; i < data.provices.length; i++) {
                    var option = "<option value='" + data.provices[i].city_code + "'>" + data.provices[i].city_name + "</option>";
                    $('#provice').append(option);
                }
                getCities($('#provice option:selected').val());
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

//选择省份城市后添加该省的市级城市
$(document).delegate("#provice", "change", function () {
    getCities($('#provice option:selected').val());
});

function getCities(city_code) {
    $('#citiesSet').empty();
    $.ajax({
        type: "POST",
        url: "/common/getcitiesbyprovice",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"city_code": city_code}),
        success: function (data) {
            if (data.status == 0) {
                for (var i = 0; i < data.cities.length; i++) {
                    var option = "<option value='" + data.cities[i].city_code + "'>" + data.cities[i].city_name + "</option>";
                    $('#citiesSet').append(option);
                }
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

//城市右移
$(document).delegate("#right", "click", function () {
    var val = $('#citiesSet option:selected').val();
    var text = $('#citiesSet').find('option:selected').text();
    $('#citiesSet option:selected').remove();
    var option = "<option value='" + val + "'>" + text + "</option>";
    $('#citiesSelect').append(option);
});

//城市左移
$(document).delegate("#left", "click", function () {
    var val = $('#citiesSelect option:selected').val();
    var text = $('#citiesSelect').find('option:selected').text();
    $('#citiesSelect option:selected').remove();
    var option = "<option value='" + val + "'>" + text + "</option>";
    $('#citiesSet').append(option);
});

//添加全部城市
$(document).delegate("#addCities", "click", function () {
    var count = $("#citiesSet option").length;
    var options = '';
    for (var i = 0; i < count; i++) {
        var val = $("#citiesSet").get(0).options[i].value;
        var text = $("#citiesSet").get(0).options[i].text;
        options += "<option value='" + val + "'>" + text + "</option>";
    }
    $('#citiesSet').empty();
    $('#citiesSelect').append(options);
});

//清空城市列表
$(document).delegate("#clearCities", "click", function () {
    var count = $("#citiesSelect option").length;
    var options = '';
    for (var i = 0; i < count; i++) {
        var val = $("#citiesSelect").get(0).options[i].value;
        var text = $("#citiesSelect").get(0).options[i].text;
        options += "<option value='" + val + "'>" + text + "</option>";
    }
    $('#citiesSelect').empty();
    $('#citiesSet').append(options);
});

//上传图片前检查图片属性
$(document).delegate("#appImg", "change", function () {
    if (checkImg(this.files)) {
        $('#poster').attr('src', '');
        $('#appImgMark').hide();
        $('#appImgName').text(this.files[0].name);
    } else {
        //清空文件域
        $(this).after($(this).clone().val(""));
        $(this).remove();
        $('#appImgName').text('');
        if (!$('#poster').attr('src')) {
            $('#appImgMark').show();
        }
    }
});

$(document).delegate("#wechatImg", "change", function () {
    if (checkImg(this.files)) {
        $('#wechat_poster').attr('src', '');
        $('#wechatImgMark').hide();
        $('#wechatImgName').text(this.files[0].name);
    } else {
        //清空文件域
        $(this).after($(this).clone().val(""));
        $(this).remove();
        $('#wechatImgName').text('');
        if (!$('#wechat_poster').attr('src')) {
            $('#wechatImgMark').show();
        }
    }
});

//检查选择图片属性
function checkImg(files) {
    var rightImg = true;
    var allowExt = ".jpg,.png";
    var allowSize = 10 * 1024 * 1024;//10M
    if (files.length)
    {
        var file = files[0];
        var fileExt = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
        if (allowExt.indexOf(fileExt) != -1) //检查图片类型
        {
            if (file.size > allowSize) {//检查图片大小
                bbx_alert_error('图片大小必须在10M 以内！');
                rightImg = false;
            }
        } else {
            bbx_alert_error('图片类型只能是：.jpg,.png');
            rightImg = false;
        }
    }
    return rightImg;
}